﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels;
using System.Diagnostics;
using System.IO;
using Krile.Kernel;
using System.Threading;
using System.Runtime.Remoting;

namespace Yukkrile
{
    public static class Core
    {
        public static Plugin Plugin = null;

        public static Config Config = null;

        private static Form parent = null;
        private static TalkRequestInfo translator = null;
        private static Process ps = null;
        public static void Init(Plugin p)
        {
            parent = new Form();
            Plugin = p;

            Config = Config.LoadConfig();

            //このチャネル生成系は一度通せばいいっぽい
            // IPC Channel を作成
            IpcClientChannel clientChannel = new IpcClientChannel();
            // リモートオブジェクトを登録
            ChannelServices.RegisterChannel(clientChannel, true);

            // オブジェクトを作成
            translator = (TalkRequestInfo)Activator.GetObject(typeof(TalkRequestInfo), "ipc://krileyukkrilesub/message");
            //このチャネル生成系は一度通せばいいっぽい
            // IPC Channelを作成
            IpcServerChannel servChannel = new IpcServerChannel("krileyukkrilesubrecv");
            // リモートオブジェクトを登録

            ChannelServices.RegisterChannel(servChannel, true);

            // イベントを登録
            var m_msg = new FinishInfo();
            m_msg.OnReadFinished += new FinishInfo.FinishEventHandler(m_msg_OnReadFinished);
            RemotingServices.Marshal(m_msg, "message", typeof(FinishInfo));

            //            translator.OnReadFinished += new TalkRequestInfo.FinishEventHandler(translator_OnReadFinished);
            Process[] processes = null;
            while ((processes = GetProcesses()) != null && processes.Length > 0)
            {
                foreach (var pr in processes)
                {
                    if (pr.ProcessName == "yukkfront.exe")
                    {
                        pr.Kill();
                        Thread.Sleep(0);
                        continue;
                    }
                }
                break;
            }
            ps = new Process();
            // プロセス起動引数設定
            ps.StartInfo.FileName = Path.Combine(Bridge.Config.PluginPath, "yukkfront.exe");
            ps.StartInfo.WorkingDirectory = Bridge.Config.PluginPath;
            // プロセス起動
            ps.Start();
        }

        static void m_msg_OnReadFinished(FinishInfo.ReadFinishEventArg e)
        {
            if (e.Code != 0)
            {
                Bridge.DebugReporter.AddReport("読み上げに失敗しました。エラーコード:" + e.Code.ToString() + " - " + e.Description);
            }
            waitingReadFinished = false;
        }

        private static Process[] GetProcesses()
        {
            String strHostName = System.Environment.MachineName;    // --- マシン名の取得
            return Process.GetProcessesByName(strHostName);
        }

        static bool waitingReadFinished = true;
        public static void SendMessage(string msg)
        {
            try
            {
                translator.DataTrance(msg, Core.Config.SpeedRatio);
                while (waitingReadFinished)
                    Thread.Sleep(0);
                waitingReadFinished = true;
            }
            catch (Exception e)
            {
                Bridge.DebugReporter.AddReport(e);
            }
        }

        public static void Exit()
        {
            Config.SaveConfig();
            try
            {
                ps.Kill();
            }
            catch (InvalidOperationException) { }
            parent.Dispose();
        }
    }
}